package com.nx.platform.es.bean.modle.score;

import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.index.query.functionscore.ExponentialDecayFunctionBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;

import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class ExpDecayFunctionTimeHandler implements ScoreFunctionFieldHandler {

    @Override
    public FilterFunctionBuilder handle(ImmutableMap<String, ?> fieldConfig, Map<String, Object> params) {
        String fieldName = MapUtils.getString(fieldConfig, "fieldName");
        String scale = MapUtils.getString(fieldConfig, "scale");
        String offset = MapUtils.getString(fieldConfig, "offset");
        double decay = MapUtils.getDoubleValue(fieldConfig, "decay", 0.5d);
        float weight = MapUtils.getFloatValue(fieldConfig, "weight", 0f);
        int precision = MapUtils.getIntValue(fieldConfig, "precision");
        ExponentialDecayFunctionBuilder function;
        if (precision <= 0) {
            function = ScoreFunctionBuilders.exponentialDecayFunction(fieldName, null, scale, offset, decay);
        } else {
            long now = System.currentTimeMillis();
            now = (now / precision) * precision;
            function = ScoreFunctionBuilders.exponentialDecayFunction(fieldName, now, scale, offset, decay);
        }
        if (weight > 0) {
            function.setWeight(weight);
        }
        return new FilterFunctionBuilder(function);
    }

}
